const _ = require('lodash');
const prefix = '/api/user';

module.exports = app => {
  const {router, model} = app;

  /** 登录 */
  router.post(prefix + '/login', async ctx => {
    const post = ctx.request.body;
    const user = await model.User.findOne(
      {where: {username: post.username, password: post.password}});
    if (!user)
      return ctx.helper.error('账号或密码错误');
    ctx.cookies.set('token',
      JSON.stringify({user: {id: user.id}, login: Date.now()}),
      {encrypt: true, maxAge: 360 * 24 * 3600 * 1000});
    ctx.body = 'ok';
  });

  /** 登出 */
  router.get(prefix + '/logout', async ctx => {
    ctx.cookies.set('token', null);
    ctx.body = 'ok';
  });

  /** 检查登录状态 */
  router.get(prefix + '/check-login', async ctx => {
    const token = ctx.cookies.get('token', {encrypt: true});
    if (_.isEmpty(token))
      return ctx.helper.error('没有登录');
    ctx.body = await model.User.findById(JSON.parse(token).user.id);
  });
};